#include "HandlerV4.h"

#include <zlib.h>

HandlerV4::HandlerV4(QObject *parent)
    : HandlerV2(parent)
{
}

void HandlerV4::GetSpriteListFromDataStream(Album &album, QDataStream *streamPtr)
{
    int colorCount = ReadInt(streamPtr);

    album.ColorLists.clear();
    QList<QColor> colorList;
    for (int i = 0; i < colorCount; i++) {
        int r = ReadByteFromDataStream(streamPtr);
        int g = ReadByteFromDataStream(streamPtr);
        int b = ReadByteFromDataStream(streamPtr);
        int a = ReadByteFromDataStream(streamPtr);
        QColor color(r, g, b, a);
        colorList.append(color);
    }
    album.ColorLists.append(colorList);

    HandlerV2::GetSpriteListFromDataStream(album, streamPtr);
}

QImage HandlerV4::GetSpriteImg(const Album &album, const SpriteStruct &sprite)
{
    QImage img;
    if (sprite.Type == SpriteTypeEnum::Argb1555 &&
        sprite.CompressMode == CompressModeEnum::Zlib) {
        const QByteArray &ba = album.SpritesDataBa.mid(sprite.DataOffset, sprite.Length);
        uchar *imgData = (uchar *)(ba.data());
        int imgDataLength = sprite.Length;

        const int size = sprite.Width * sprite.Height;
        unsigned char uncompressBuffer[size];
        uLong uncompressBufferLen = size;
        uchar *compressBuffer = imgData;
        uLong compressBufferLen = imgDataLength;
        int err = uncompress(uncompressBuffer, &uncompressBufferLen, compressBuffer, compressBufferLen);
        if (err != Z_OK) {
            qCritical() << Q_FUNC_INFO << "data uncompress failed, err code:" << err;
            return img;
        }
        imgData = uncompressBuffer;
        imgDataLength = uncompressBufferLen;

        // 按照色表填充图像数据
        if (album.ColorLists.size() < 1 && album.ColorLists.first().size() < 1) {
            qCritical() << Q_FUNC_INFO << "album color list list is error!";
            return img;
        }
        const QList<QColor> &colorList = album.ColorLists.first();
        int filledImgDataLen = imgDataLength * 4;
        uchar filledImgData[filledImgDataLen];
        int filledImgDataIndex = 0;
        for (uchar *p = imgData; p < imgData + imgDataLength; p++) {
            uchar imgDataUChar = *p;
            int colorIndex = imgDataUChar % colorList.size();
            const QColor &color = colorList.at(colorIndex);
            filledImgData[filledImgDataIndex] = color.blue();
            filledImgData[filledImgDataIndex + 1] = color.green();
            filledImgData[filledImgDataIndex + 2] = color.red();
            filledImgData[filledImgDataIndex + 3] = color.alpha();
            filledImgDataIndex += 4;
        }

        GetImgFromUCharArray(img, sprite.Width, sprite.Height,
                            filledImgData, filledImgDataLen, sprite.Type);
        return img;
    }

    return HandlerV2::GetSpriteImg(album, sprite);
}
